﻿using System;
using System.Configuration;
using System.IO;

namespace NetstsadmService
{
    internal class Config
    {
        internal enum ConfigKeys
        {
            Port_Number,
            Allow_Anonymous
        }

        static Config instance = null;
        static readonly object padlock = new object();

        Configuration Configuration;

        static internal Config GetConfig()
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Config();
                }
                return instance;
            }
        }

        protected Config()
        {
            if (!File.Exists(ConfigPath))
            {
                using (StreamWriter sw = new StreamWriter(ConfigPath))
                {
                    sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                    sw.WriteLine("<configuration>");
                    sw.WriteLine("  <appSettings>");
                    sw.WriteLine("    <add key=\"Port_Number\" value=\"\" />");
                    sw.WriteLine("    <add key=\"Allow_Anonymous\" value=\"\" />");
                    sw.WriteLine("  </appSettings>");
                    sw.WriteLine("</configuration>");
                }          
            }
            
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = ConfigPath;
            Configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        }

        public string ConfigPath
        {
            get { return System.IO.Path.Combine(Environment.CurrentDirectory, "NetstsadmService.exe.config"); }
        }

        public string GetValue(ConfigKeys Key)
        {
            if (Configuration.AppSettings.Settings[Key.ToString()] != null)
                return Configuration.AppSettings.Settings[Key.ToString()].Value;

            return "";
        }

        public void SetValue(ConfigKeys Key, string Value)
        {
            if (Configuration.AppSettings.Settings[Key.ToString()] != null)
                Configuration.AppSettings.Settings.Remove(Key.ToString());

            Configuration.AppSettings.Settings.Add(Key.ToString(), Value);
            Configuration.Save(ConfigurationSaveMode.Modified);
        }
    }
}
